/**
 * @description 岗位管理相关的路由处理
 * @author yishen@mdashen.com
 *
 */
const router = require('koa-router')()
const { Gangwei, Category } = require('../../db/model/index')

// 获取所有岗位名称，选传cgid
router.get('/gw/getlist', async (ctx, next) => {
  const { cgid } = ctx.request.query
  // where查询的条件对象
  let conditions = { cgid }
  if (!cgid) {
    conditions = {}
  }
  const res = await Gangwei.findAndCountAll({
    attributes: ['id', 'cgid', 'name'],
    include: [{ model: Category, attributes: ['name'] }],
    where: conditions,
  })
  const gangweiList = res.rows.map((row) => row.dataValues)
  gangweiList.map((item) => {
    item.cg = item.category.name
    delete item.category
  })
  ctx.body = {
    error_code: 0,
    msg: '获取成功',
    count: res.count,
    data: gangweiList,
  }
})
router.post('/gw/add', async (ctx, next) => {
  const { name, cgid } = ctx.request.body
  try {
    var res = await Gangwei.create({ name, cgid })
  } catch (error) {
    console.log('错误,重复添加岗位')
    console.log(error)
    ctx.body = {
      error_code: 1,
      msg: '添加失败,请检查传入条件是否异常',
    }
    return
  }
  ctx.body = {
    error_code: 0,
    msg: '添加成功',
    data: res,
  }
})
router.post('/gw/del', async (ctx, next) => {
  const { id, name } = ctx.request.body
  // 通过id删除
  if (id && id.length > 0) {
    const res = await Gangwei.destroy({
      where: {
        id,
      },
    })
    if (res === 1) {
      ctx.body = { error_code: 0, msg: `删除成功、数据库受影响:${res}行` }
      return
    } else {
      ctx.body = { error_code: 1, msg: '发生错误，请检查传入的id是否错误' }
      return
    }
  }
  // 通过name删除
  if (name && name.length > 0) {
    const res = await Gangwei.destroy({
      where: {
        name,
      },
    })
    if (res === 1) {
      ctx.body = { error_code: 0, msg: `删除成功、数据库受影响:${res}行` }
      return
    } else {
      ctx.body = {
        error_code: 1,
        msg: '发生错误，请检查传入的岗位名称是否错误',
      }
      return
    }
  }
  ctx.body = { error_code: 1, msg: '传入值为空，请检查传入数据是否正确' }
})
module.exports = router
